import model.ListNode;

public class ReverseKGroup {
    //k个一组翻转链表
    public ListNode code(ListNode head, int k) {
        //计算一共有多少组
        int count = 0;
        ListNode cur = head;
        while (cur != null){
            count++;
            cur = cur.next;
        }
        int n = count / k;

        ListNode newHead = new ListNode(0);
        ListNode prev = newHead;
        cur = head;

        for (int i = 0; i < n; i++){
            ListNode tmp = cur;
            //进行其中一组的头插排序
            for (int j = 0; j < k; j++){
                ListNode next = cur.next;
                cur.next = prev.next;
                prev.next = cur;
                cur = next;
            }

            prev = tmp;
        }

        prev.next = cur;
        return newHead.next;
    }
}
